package com.nartosoft.tubuloader;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.File;

/**
 * @author eb
 * 
 * Writes upload results (and, if requested via the 'verbose' switch, error
 * messages) to the clipboard.
 */
public class ClipboardWriter implements EventListener {
	public static final String TEMPLATE_URL_PLACEHOLDER = "%s";

	public static final String TEMPLATE_FILENAME_PLACEHOLDER = "%n";

	public static final String DEFAULT_TEMPLATE = TEMPLATE_URL_PLACEHOLDER;

	private String clipboardContent = "";

	private final boolean verbose;

	private final String template;

	public ClipboardWriter(boolean verbose, String template) {
		this.verbose = verbose;
		this.template = template;
	}

	public void onUpload(String fileName, String url) {
		writeToClipboard(template
				.replaceAll(TEMPLATE_URL_PLACEHOLDER, url)
				.replaceAll(TEMPLATE_FILENAME_PLACEHOLDER, new File(fileName).getName()));
	}

	public void onError(String message) {
		if (verbose) {
			writeToClipboard("ERROR: " + message);
		}
	}

	private void writeToClipboard(String text) {
		if(clipboardContent.length()>0) {
			clipboardContent += "\n";
		}
		clipboardContent += text;
	}

	/**
	 * Copies data to clipboard.
	 */
	public void onAllFilesDone() {
		StringSelection sc = new StringSelection(clipboardContent);
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		clipboard.setContents(sc, sc);
	}
}
